<template>
  <div class="role-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>角色管理</span>
          <el-button type="primary" @click="handleAdd">新增角色</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :model="searchForm" inline>
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.roleName" placeholder="请输入角色名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table :data="tableData" v-loading="loading" border>
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="roleId" label="角色ID" width="80" align="center" />
        <el-table-column prop="roleName" label="角色名称" min-width="120" />
        <el-table-column prop="roleDesc" label="角色描述" min-width="150" />
        <el-table-column prop="userCount" label="用户数量" width="100" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.userCount > 0" type="primary">
              {{ row.userCount }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
<!--        <el-table-column label="菜单权限" min-width="150">-->
<!--          <template #default="{ row }">-->
<!--            <el-tag-->
<!--                v-for="menuId in row.menuIds"-->
<!--                :key="menuId"-->
<!--                size="small"-->
<!--                style="margin-right: 5px; margin-bottom: 5px;"-->
<!--            >-->
<!--              {{ getMenuName(menuId) }}-->
<!--            </el-tag>-->
<!--            <span v-if="!row.menuIds || row.menuIds.length === 0">-</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column prop="createTime" label="创建时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="primary" @click="handleMenu(row)">分配菜单</el-button>
            <el-button size="small" type="info" @click="handleViewUsers(row)">查看用户</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
            layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="500px"
        @close="handleDialogClose"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input
              v-model="form.roleDesc"
              type="textarea"
              :rows="3"
              placeholder="请输入角色描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 分配菜单对话框 -->
    <el-dialog title="分配菜单权限" v-model="menuDialogVisible" width="600px" @open="handleMenuDialogOpen">
      <div class="menu-tree">
        <el-tree
            ref="menuTreeRef"
            :data="menuTreeData"
            show-checkbox
            node-key="menuId"
            :default-expand-all="true"
            :props="treeProps"
            :check-strictly="true"
        />
      </div>
      <template #footer>
        <el-button @click="menuDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleMenuSubmit" :loading="menuSubmitLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 查看用户对话框 -->
    <el-dialog title="角色用户列表" v-model="userDialogVisible" width="700px">
      <el-table :data="roleUsers" border v-loading="userLoading">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="adminUserId" label="用户ID" width="80" align="center" />
        <el-table-column prop="loginUserName" label="用户名" min-width="120" />
        <el-table-column prop="nickName" label="昵称" min-width="120" />
        <el-table-column prop="locked" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.locked === 0 ? 'success' : 'danger'" size="small">
              {{ row.locked === 0 ? '正常' : '锁定' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="userDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getRoleList, addRole, updateRole, deleteRole, updateRoleMenus, getRoleUsers, getRoleMenus } from '@/utils/role'
import { getAllMenus } from '@/utils/menu'

const loading = ref(false)
const submitLoading = ref(false)
const menuSubmitLoading = ref(false)
const userLoading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const searchForm = reactive({
  roleName: ''
})

const form = reactive({
  roleId: null,
  roleName: '',
  roleDesc: ''
})

const rules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '角色名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  roleDesc: [
    { required: true, message: '请输入角色描述', trigger: 'blur' },
    { max: 200, message: '角色描述不能超过 200 个字符', trigger: 'blur' }
  ]
}

const dialogVisible = ref(false)
const dialogTitle = ref('')
const isAdd = ref(true)
const formRef = ref()

// 菜单相关
const menuDialogVisible = ref(false)
const menuTreeData = ref([])
const menuTreeRef = ref()
const treeProps = {
  children: 'children',
  label: 'menuName'
}
const currentRoleId = ref(null)
const currentRoleMenuIds = ref([]) // 存储当前角色的菜单ID

// 用户相关
const userDialogVisible = ref(false)
const roleUsers = ref([])

// 所有菜单数据（用于显示菜单名称）
const allMenus = ref([])

// 格式化时间
const formatTime = (time) => {
  if (!time) return '-'
  return new Date(time).toLocaleString()
}

// 根据菜单ID获取菜单名称
const getMenuName = (menuId) => {
  const menu = allMenus.value.find(m => m.menuId === menuId)
  return menu ? menu.menuName : '未知菜单'
}

// 获取角色列表 - 修改为与用户管理相同的处理方式
const getRoleListData = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      ...searchForm
    }
    console.log('请求参数:', params)

    const res = await getRoleList(params)
    console.log('角色列表返回数据:', res)

    // 直接使用返回的数据，不检查 resultCode
    if (res) {
      tableData.value = res
      total.value = res.length
      console.log('表格数据已设置:', tableData.value)

      // 为每个角色获取菜单权限
      await getRolesMenuPermissions()
    } else {
      tableData.value = []
      total.value = 0
      console.warn('返回数据格式异常:', res)
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    // 不显示错误消息，因为可能是响应拦截器的问题
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 获取所有角色的菜单权限
const getRolesMenuPermissions = async () => {
  try {
    // 为每个角色获取菜单权限
    for (const role of tableData.value) {
      try {
        const menuRes = await getRoleMenus(role.roleId)
        console.log(`角色 ${role.roleName} 的菜单权限:`, menuRes)

        if (menuRes && Array.isArray(menuRes)) {
          role.menuIds = menuRes
        } else {
          role.menuIds = []
        }
      } catch (error) {
        console.error(`获取角色 ${role.roleName} 的菜单权限失败:`, error)
        role.menuIds = []
      }
    }
    console.log('所有角色的菜单权限已更新:', tableData.value)
  } catch (error) {
    console.error('获取角色菜单权限失败:', error)
  }
}

// 获取菜单树 - 修改为与用户管理相同的处理方式
const getMenuTreeData = async () => {
  try {
    const res = await getAllMenus()
    console.log('菜单树返回数据:', res)

    // 直接使用返回的数据
    if (res) {
      menuTreeData.value = res
      allMenus.value = res // 保存所有菜单数据用于显示菜单名称
    } else {
      menuTreeData.value = []
      allMenus.value = []
      console.warn('菜单树返回数据格式异常:', res)
    }
  } catch (error) {
    console.error('获取菜单树失败:', error)
    menuTreeData.value = []
    allMenus.value = []
  }
}

// 获取角色用户 - 修改为与用户管理相同的处理方式
const getRoleUsersData = async (roleId) => {
  userLoading.value = true
  try {
    const res = await getRoleUsers(roleId)
    console.log('角色用户返回数据:', res)

    // 直接使用返回的数据
    if (res) {
      roleUsers.value = res
    } else {
      roleUsers.value = []
      console.warn('角色用户返回数据格式异常:', res)
    }
  } catch (error) {
    console.error('获取角色用户失败:', error)
    roleUsers.value = []
  } finally {
    userLoading.value = false
  }
}

// 获取单个角色的菜单权限
const getRoleMenuIds = async (roleId) => {
  try {
    const res = await getRoleMenus(roleId)
    console.log(`角色 ${roleId} 的菜单权限:`, res)

    if (res && Array.isArray(res)) {
      return res
    } else {
      return []
    }
  } catch (error) {
    console.error(`获取角色 ${roleId} 的菜单权限失败:`, error)
    return []
  }
}

const handleMenuDialogOpen = async () => {
  if (currentRoleId.value) {
    try {
      const menuIds = await getRoleMenuIds(currentRoleId.value)
      currentRoleMenuIds.value = menuIds
      console.log('当前角色的菜单ID:', currentRoleMenuIds.value)

      // 详细调试菜单树数据
      console.log('完整的菜单树数据:', menuTreeData.value)

      // 检查菜单树中是否真的没有ID为10的菜单
      const hasMenu10 = checkMenuExists(menuTreeData.value, 10)
      console.log('菜单树中是否存在ID为10的菜单:', hasMenu10)

      // 获取所有菜单ID
      const allMenuIds = getAllMenuIds(menuTreeData.value)
      console.log('菜单树中所有可用的菜单ID:', allMenuIds.sort((a, b) => a - b))

      // 过滤掉不存在的菜单ID
      const validMenuIds = menuIds.filter(id => allMenuIds.includes(id))
      const invalidMenuIds = menuIds.filter(id => !allMenuIds.includes(id))
      console.log('有效的菜单ID:', validMenuIds)
      console.log('无效的菜单ID(不存在于菜单树中):', invalidMenuIds)

      if (menuTreeRef.value) {
        // 先清空所有选中
        menuTreeRef.value.setCheckedKeys([])
        // 只设置有效的菜单ID
        if (validMenuIds.length > 0) {
          menuTreeRef.value.setCheckedKeys(validMenuIds)
          console.log('已设置选中菜单:', validMenuIds)
        } else {
          console.log('没有有效的菜单ID可选中')
        }

        // 验证实际选中的菜单
        const actualChecked = menuTreeRef.value.getCheckedKeys()
        console.log('实际选中的菜单ID:', actualChecked)
      }
    } catch (error) {
      console.error('获取角色菜单权限失败:', error)
      if (menuTreeRef.value) {
        menuTreeRef.value.setCheckedKeys([])
      }
    }
  }
}

// 检查菜单是否存在
const checkMenuExists = (menuData, menuId) => {
  const findMenu = (nodes) => {
    if (!nodes || !Array.isArray(nodes)) return false
    for (const node of nodes) {
      if (node.menuId === menuId) return true
      if (node.children && findMenu(node.children)) return true
    }
    return false
  }
  return findMenu(menuData)
}

// 递归获取所有菜单ID
const getAllMenuIds = (menuData) => {
  const ids = []
  const traverse = (nodes) => {
    if (!nodes || !Array.isArray(nodes)) return
    nodes.forEach(node => {
      if (node.menuId) {
        ids.push(node.menuId)
      }
      if (node.children) {
        traverse(node.children)
      }
    })
  }
  traverse(menuData)
  return ids
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getRoleListData()
}

// 重置
const handleReset = () => {
  searchForm.roleName = ''
  handleSearch()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增角色'
  isAdd.value = true
  Object.keys(form).forEach(key => {
    form[key] = ''
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑角色'
  isAdd.value = false
  Object.assign(form, { ...row })
  dialogVisible.value = true
}

// 分配菜单
const handleMenu = async (row) => {
  currentRoleId.value = row.roleId

  // 获取菜单数据
  await getMenuTreeData()

  // 打开对话框
  menuDialogVisible.value = true
}

// 查看用户
const handleViewUsers = async (row) => {
  await getRoleUsersData(row.roleId)
  userDialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  if (row.userCount > 0) {
    ElMessage.warning(`该角色下有 ${row.userCount} 个用户，无法删除`)
    return
  }

  ElMessageBox.confirm(`确定删除角色 "${row.roleName}" 吗？`, '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    try {
      const res = await deleteRole(row.roleId)
      if (res) {
        ElMessage.success('删除成功')
        getRoleListData()
      } else {
        ElMessage.error('删除失败')
      }
    } catch (error) {
      console.error('删除角色失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 对话框关闭
const handleDialogClose = () => {
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitLoading.value = true

    let res
    if (isAdd.value) {
      res = await addRole(form)
    } else {
      res = await updateRole(form)
    }

    if (res) {
      ElMessage.success('操作成功')
      dialogVisible.value = false
      getRoleListData()
    } else {
      ElMessage.error('操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    if (error.errors) {
      return
    }
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 提交菜单分配
const handleMenuSubmit = async () => {
  try {
    menuSubmitLoading.value = true

    // 确保菜单树引用存在
    if (!menuTreeRef.value) {
      ElMessage.error('菜单树未初始化')
      return
    }

    const checkedKeys = menuTreeRef.value.getCheckedKeys()
    const halfCheckedKeys = menuTreeRef.value.getHalfCheckedKeys()
    const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys]

    const res = await updateRoleMenus(currentRoleId.value, allCheckedKeys)
    console.log("API返回结果:", res)

    // 根据API返回结构判断成功与否
    if (res && res.resultCode === 200) {
      ElMessage.success(res.message || '分配菜单权限成功')
      menuDialogVisible.value = false
      getRoleListData()
    } else {
      ElMessage.error(res?.message || '分配菜单权限失败')
    }
  } catch (error) {
    console.error('分配菜单权限失败:', error)
    ElMessage.error('分配菜单权限失败')
  } finally {
    menuSubmitLoading.value = false
  }
}

// 分页
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
  getRoleListData()
}

const handlePageChange = () => {
  getRoleListData()
}

onMounted(() => {
  getRoleListData()
  getMenuTreeData()
})
</script>

<style scoped>
.role-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.menu-tree {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
}

:deep(.el-table .cell) {
  white-space: nowrap;
}
</style>
